﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MouseExtender.WebSite.Logic.DataEntities;

namespace MouseExtender.WebSite.Logic.Managers
{
    public class ErrorReportsManager
    {
        public ErrorReportEntity[] GenerateReport(DateTime dateFrom, DateTime dateTo, bool includeNonCritical)
        {
            using (MEDBDataContext medb = new MEDBDataContext())
            {
                var reportQuery = from r in medb.ErrorReports
                                  where r.ReportTime >= dateFrom && r.ReportTime <= dateTo
                                  group r by new { r.ErrorMessage, r.IsCritical } into g
                                  select new ErrorReportEntity()
                                  {
                                      ErrorMessage = g.Key.ErrorMessage,
                                      Quantity = g.Count(),
                                      LastErrorTime = g.Max(r => r.ReportTime),
                                      MaxVersion = g.Max(r => r.ApplicationVersion),
                                      IsCritical = g.Key.IsCritical
                                  };

                if (includeNonCritical)
                {
                    reportQuery = reportQuery.OrderByDescending(r => r.IsCritical);
                }
                else
                {
                    reportQuery = reportQuery.Where(r => r.IsCritical);
                }

                reportQuery = reportQuery.OrderByDescending(r => r.Quantity);

                return reportQuery.ToArray();
            }
        }
    }
}

//declare @startDate date = getdate()

//select 
//    ErrorMessage, 
//    count(ErrorMessage) as Quant,
//    max(ApplicationVersion),
//    max(ReportTime),
//    IsCritical
//from ErrorReport
//where ReportTime >= @startDate
//group by ErrorMessage, IsCritical
//order by IsCritical desc, Quant desc